package com.wy.panda.common.page;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wy.panda.common.util.BeanUtils;
import com.wy.panda.common.util.CollectionUtils;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import ma.glasnost.orika.metadata.TypeBuilder;
import ma.glasnost.orika.metadata.TypeFactory;

/**
 * 分页查询结果类
 * @author wangyuan
 * @since 2020年3月21日 下午2:16:16
 *
 * @param <T>
 */
@ApiModel("通用分页模型")
@Data
public class PageResult<T> implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -74610238125451859L;
	/**
	 * 总记录数
	 */
	@ApiModelProperty("总记录数")
	private int total;
	/**
	 * 每页记录数
	 */
	@ApiModelProperty("每页记录数")
	private int size;
	/**
	 * 总页数
	 */
	@ApiModelProperty("总页数")
	private int totalPage;
	/**
	 * 当前页数
	 */
	@ApiModelProperty("当前页数")
	private int current;
	/**
	 * 结果
	 */
	@ApiModelProperty("数据集")
	private List<T> data;

	/**
	 * 分页
	 * @param data        列表数据
	 * @param total  总记录数
	 * @param pageSize    每页记录数
	 * @param currPage    当前页数
	 */
	public PageResult(List<T> data, int total, int size, int current) {
		this.data = CollectionUtils.isEmpty(data) ? Collections.emptyList() : data;
		this.total = total;
		this.size = size;
		this.current = current;
		this.totalPage = (int) Math.ceil((double) total / size);
	}

	/**
	 * 分页
	 */
	public PageResult(IPage<T> page) {
		data = CollectionUtils.isEmpty(page.getRecords()) ? Collections.emptyList() : page.getRecords();
		total = (int) page.getTotal();
		size = (int) page.getSize();
		current = (int) page.getCurrent();
		totalPage = (int) page.getPages();
	}
	
	/**
	 * 类型转换
	 * @param sourceClass
	 * @param destinationClass
	 * @return
	 */
	@SuppressWarnings("unchecked")
    public <S, D> PageResult<D> convert(Class<S> sourceClass, Class<D> destinationClass) {
	    return BeanUtils.mapperFacade().map((PageResult<S>) this, 
	            new TypeBuilder<PageResult<S>>(TypeFactory.valueOf(sourceClass)) {}.build(), 
	            new TypeBuilder<PageResult<D>>(TypeFactory.valueOf(destinationClass)) {}.build());
	}
	
	public static <T> PageResult<T> build(IPage<T> page) {
	    return new PageResult<>(page);
    }
	
	public static <T> PageResult<T> build(List<T> data, int total, int size, int current) {
        return new PageResult<>(data, total, size, current);
    }
}
